package com.haixinga.commbiz.commons.exception;

import com.haixinga.commbiz.commons.vo.ApiRes;
import com.haixinga.commbiz.commons.constants.ApiCodeEnum;
import com.haixinga.commbiz.commons.utils.HttpKit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author terrfly
 * @Date 2020/3/29 15:45
 * @Description 通用业务异常处理类
 **/
@Configuration
public class BizExceptionResolver implements HandlerExceptionResolver {

	private Logger logger = LogManager.getLogger(BizExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {


		String outPutJson;

		//业务异常
        if(ex instanceof BizException) {
        	logger.error("公共捕捉[Biz]异常：{}",ex.getMessage());
			outPutJson = ((BizException) ex).getApiRes().toJSONString();
        }else{
        	logger.error("公共捕捉[Exception]异常：",ex);
			outPutJson = ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, ex.getMessage()).toJSONString();
        }

        try {
	   			HttpKit.outPutJson(response, outPutJson);
   		} catch (IOException e) {
   			logger.error("输出错误信息异常:", e);
   		}

   		return new ModelAndView();
	}

}
